package com.neusoft.lohas.common.pay.payutil.unionpay.service;

import java.util.Map;

import com.neusoft.lohas.common.pay.payutil.unionpay.conf.SklConfig;
import com.neusoft.lohas.common.pay.payutil.unionpay.util.HttpUtil;
import com.neusoft.lohas.common.pay.payutil.unionpay.util.SklCore;

/**
 * Created with IntelliJ IDEA.
 * User: HS-AVA
 * Date: 14-1-8
 * Time: 上午9:50
 * To change this template use File | Settings | File Templates.
 */
public class SklService {
	public static void main(String args[]) {

	}

	/**
	 * 交易接口处理
	 * @param req 请求要素
	 * @param resp 应答要素
	 * @return 是否成功
	 */
	public static boolean trade(Map<String, String> req,
			Map<String, String> resp) {
		String nvp = buildReq(req);
		String respString = HttpUtil.post(SklConfig.TRADE_URL, nvp);
		return verifyResponse(respString, resp);
	}

	/**
	 * 交易查询处理
	 * @param req 请求要素
	 * @param resp 应答要素
	 * @return 是否成功
	 */
	public static boolean query(Map<String, String> req,
			Map<String, String> resp) {
		String nvp = buildReq(req);
		String respString = HttpUtil.post(SklConfig.QUERY_URL, nvp);
		return verifyResponse(respString, resp);
	}

	/**
	 * 拼接保留域
	 * @param req 请求要素
	 * @return 保留域
	 */
	public static String buildReserved(Map<String, String> req) {
		StringBuilder merReserved = new StringBuilder();
		merReserved.append("{");
		merReserved.append(SklCore.createLinkString(req, false, true));
		merReserved.append("}");
		return merReserved.toString();
	}

	/**
	 * 拼接请求字符串
	 * @param req 请求要素
	 * @param resp 应答要素
	 * @return 请求字符串
	 */
	public static String buildReq(Map<String, String> req) {
		// 除去数组中的空值和签名参数
		Map<String, String> filteredReq = SklCore.paraFilter(req);
		// 生成签名结果
		String signature = SklCore.buildSignature(filteredReq);

		// 签名结果与签名方式加入请求提交参数组中
		filteredReq.put(SklConfig.SIGNATURE, signature);
		filteredReq.put(SklConfig.SIGN_METHOD, SklConfig.SIGN_TYPE);

		return SklCore.createLinkString(filteredReq, false, true);
	}

	/**
	 * 异步通知消息验证
	 * @param para 异步通知消息
	 * @return 验证结果
	 */
	public static boolean verifySignature(Map<String, String> para) {
		String respSignature = para.get(SklConfig.SIGNATURE);
		// 除去数组中的空值和签名参数
		Map<String, String> filteredReq = SklCore.paraFilter(para);
		String signature = SklCore.buildSignature(filteredReq);
		if (null != respSignature && respSignature.equals(signature)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 应答解析
	 * @param respString 应答报文
	 * @param resp 应答要素
	 * @return 应答是否成功
	 */
	private static boolean verifyResponse(String respString,
			Map<String, String> resp) {
		if (respString != null && !"".equals(respString)) {
			// 请求要素
			Map<String, String> para;
			try {
				para = SklCore.parseQString(respString);
			} catch (Exception e) {
				return false;
			}
			boolean signIsValid = verifySignature(para);

			resp.putAll(para);

			if (signIsValid) {
				return true;
			} else {
				return false;
			}

		}
		return false;
	}
}
